<?php



/**
 * Radcodes - SocialEngine Module
 *
 * @category   Application_Extensions
 * @package    Education
 * @copyright  Copyright (c) 2009-2010 Radcodes LLC (http://www.radcodes.com)
 * @license    http://www.radcodes.com/license/
 * @version    $Id$
 * @author     Vincent Van <vincent@radcodes.com>
 */
 
 
 
class Education_Api_Core extends Core_Api_Abstract
{
  const IMAGE_WIDTH = 720;
  const IMAGE_HEIGHT = 720;

  const THUMB_WIDTH = 140;
  const THUMB_HEIGHT = 160;
  
  public function getCategories()
  {
    $table = Engine_Api::_()->getDbtable('categories', 'education');
    $categories = $table->fetchAll($table->select()->order('order'));
    
    return $categories;
  }
  
  public function getCategory($category_id)
  {
  	static $categories = array();
  	
  	if (!isset($categories[$category_id]))
  	{
  		$categories[$category_id] = Engine_Api::_()->getDbtable('categories', 'education')->find($category_id)->current();
  	}
  	
    return $categories[$category_id];
  }
  
  public function convertCategoriesToArray($categories)
  {
    $categories_prepared = array();
    foreach ($categories as $category){
      $categories_prepared[$category->category_id]= $category->category_name;
    }
    return $categories_prepared;
  }
  
  
  public function countEducations($params = array())
  {
    $paginator = $this->getEducationsPaginator($params);
    return $paginator->getTotalItemCount();  
  }
  
  // Select
  /**
   * Gets a paginator for educations
   *
   * @param Core_Model_Item_Abstract $user The user to get the messages for
   * @return Zend_Paginator
   */
  public function getEducationsPaginator($params = array(), $options = null)
  {
    $paginator = Zend_Paginator::factory($this->getEducationsSelect($params, $options));
    if( !empty($params['page']) )
    {
      $paginator->setCurrentPageNumber($params['page']);
    }
    if( !empty($params['limit']) )
    {
      $paginator->setItemCountPerPage($params['limit']);
    }
    return $paginator;
  }

  /**
   * Gets a select object for the user's education entries
   *
   * @param Core_Model_Item_Abstract $user The user to get the messages for
   * @return Zend_Db_Table_Select
   */
  public function getEducationsSelect($params = array(), $options = null)
  {
    $table = $this->getEducationTable();
    
    $rName = $table->info('name');

    $select = $table->select();
    
    if (isset($params['user'])) 
    {
      $user = Engine_Api::_()->user()->getUser($params['user']);
      $select->where($rName.'.user_id = ?', $user->getIdentity());
    }
    
    if (isset($params['category']))
    {
      $category_id = ($params['category'] instanceof Education_Model_Category) ? $params['category']->getIdentity() : $params['category'];
      $select->where($rName.'.category_id = ?', $category_id);
    }
    
    if (isset($params['featured'])) 
    {
      $select->where($rName.'.featured = ?', $params['featured'] ? 1 : 0);
    }
  
    if (isset($params['search']))
    {
      $select->where($rName.'.search = ?', $params['search'] ? 1 : 0);
    }
    
    if( !empty($params['keyword']) )
    {
      $select->where($rName.".title LIKE ? OR ".$rName.".description LIKE ? OR ".$rName.".keywords LIKE ?", '%'.$params['keyword'].'%');
    }

    if (isset($params['class_year']))
    {
      $select->where($rName.'.class_year = ?', $params['class_year']);
    }
    
    foreach (array('title','concentration','minor','degree') as $field)
    {
      if (isset($params[$field]))
      {
        $select->where($rName.".$field LIKE ?", '%'.$params[$field].'%');
      }
    }
    
    if( !empty($params['start_date']) )
    {
      $select->where($rName.".creation_date >= ?", date('Y-m-d', $params['start_date']));
    }

    if( !empty($params['end_date']) )
    {
      $select->where($rName.".creation_date <= ?", date('Y-m-d', $params['end_date']));
    }
    
    // Process options
    $tmp = array();
    foreach( $params as $k => $v ) {
      if( null == $v || '' == $v || (is_array($v) && count(array_filter($v)) == 0) ) {
        continue;
      } else if( false !== strpos($k, '_field_') ) {
        list($null, $field) = explode('_field_', $k);
        $tmp['field_' . $field] = $v;
      } else if( false !== strpos($k, '_alias_') ) {
        list($null, $alias) = explode('_alias_', $k);
        $tmp[$alias] = $v;
      } else {
        $tmp[$k] = $v;
      }
    }
    $params = $tmp;     
    
    // Build search part of query
    $searchParts = Engine_Api::_()->fields()->getSearchQuery('education', $params);
    if (!empty($searchParts))
    {
      $searchTable = Engine_Api::_()->fields()->getTable('education', 'search')->info('name');
      
      $select = $select
        ->setIntegrityCheck(false)
        ->from($rName)
        ->joinLeft($searchTable, "$searchTable.item_id = $rName.education_id")
        ->group("$rName.education_id");     
      foreach( $searchParts as $k => $v ) 
      {
        $select = $select->where("`{$searchTable}`.{$k}", $v);
      }
    }      
    
    if( !empty($params['tag']) )
    {          
      $tagTable = Engine_Api::_()->getDbtable('TagMaps', 'core')->info('name');
      
      $select = $select
        ->setIntegrityCheck(false)
        ->from($rName)
        ->joinLeft($tagTable, "$tagTable.resource_id = $rName.education_id")
        ->where($tagTable.'.resource_type = ?', 'education')
        ->where($tagTable.'.tag_id = ?', $params['tag']);
    }

    if (empty($params['order'])) {
      $params['order'] = 'recent';
    }    
    
    if (isset($params['order'])) 
    {
      switch ($params['order'])
      {
        case 'random':
          $order_expr = new Zend_Db_Expr('RAND()');
          break;
        case 'recent':
          $order_expr = $rName.".creation_date DESC";
          break;
        case 'lastupdated':
          $order_expr = $rName.".modified_date DESC";
          break;
        case 'mostcommented':
          $order_expr = $rName.".comment_count DESC";
          break;
        case 'mostliked':
          $order_expr = $rName.".like_count DESC";
          break;  
        case 'mostviewed':
          $order_expr = $rName.".view_count DESC";
          break;
        case 'alphabet':
          $order_expr = $rName.".title ASC";
          break;
        case 'year':
          $order_expr = $rName.".class_year DESC";
          break;
        default:
          $order_expr = !empty($params['order']) ? $params['order'] : $rName.'.creation_date DESC';
          
          if (!empty($params['order_direction'])) {
            $order_expr .= " " .$params['order_direction'];
          }
          
          if (!($order_expr instanceof Zend_Db_Expr) and strpos($order_expr, '.') === false) {
            $order_expr = $rName.".".trim($order_expr);
          }
      }
      $select->order( $order_expr );
      unset($params['order']);
    }    
    
    return $select;
  }

  
  public function filterEmptyParams($values)
  {
    foreach ($values as $key => $value)
    {
      if (is_array($value))
      {
        foreach ($value as $value_k => $value_v)
        {
          if (!strlen($value_v))
          {
            unset($value[$value_k]);
          }
        }
      }
      
      if (is_array($value) && count($value) == 0)
      {
        unset($values[$key]);
      }
      else if (!is_array($value) && !strlen($value))
      {
        unset($values[$key]);
      }
    }
    
    return $values;
  }
  
  public function getPopularTags($options = array())
  {
    $tags = Engine_Api::_()->radcodes()->getPopularTags('education', $options);
    return $tags;
  }  
  

  /***
   * @return Education_Model_DbTable_Educations
   */
  public function getEducationTable()
  {
    return Engine_Api::_()->getDbtable('educations', 'education');
  }
  
}